package commonUtils.utils;

import cn.hutool.core.bean.BeanUtil;

import commonUtils.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ReflashInterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;

    public ReflashInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TODO 获取请求头中的token
        String token = request.getHeader("authorization");
        log.info("token的值为"+token);
        if (token == null){
            return true;
        }
        //TODO 基于redis获取用户
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(tokenKey);

        //TODO 判断用户是否存在
        if (map.isEmpty()){
            return true;
        }

        //TODO 将查询到的hash数据转换成user对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(map, new UserDTO(), false);
        //存在，保存信息到ThreadLocal
        UserHolder.saveUser(userDTO);

        //TODO 刷新token有效期
        stringRedisTemplate.expire(tokenKey,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //TODO 放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();

    }
}
